import React, { memo,useCallback} from 'react'
import { shallowEqual, useDispatch, useSelector } from 'react-redux'
import { message } from 'antd'

import {
  changePlayStatusAction,
  changeCurrentIndexAndSongAction
} from '../../../store/actionCreator'
import{ ControlWrapper} from './style'

function Control(props){

  // redux hook
  const dispatch = useDispatch()
  const {
    playStatus,
    playlistCount
  } = useSelector(
    (state) => ({
      playStatus: state.getIn(['player', 'playStatus']),
      playlistCount: state.getIn(['player', 'playListCount'])
    }),
    shallowEqual
  )

  // other function
  // 点击播放或暂停按钮后音乐
  const playMusic = useCallback(() => {
    dispatch(changePlayStatusAction(!playStatus))
  }, [playStatus])
  
  const changeSong = (tag)=>{
    if (playlistCount < 1) {
      message.error('请添加播放列表', 0.5)
      return
    }
    // 需要需要派发action,所以具体逻辑在actionCreator中完成
    dispatch(changeCurrentIndexAndSongAction(tag))
    dispatch(changePlayStatusAction(true + Math.random()))
  }

  return (
    <ControlWrapper  playStatus={playStatus}>
      <button
        className="sprite_player pre"
        onClick={(e) => changeSong(-1)}
      ></button>
      <button className="sprite_player play" onClick = {playMusic}></button>
      <button
        className="sprite_player next"
        onClick={(e) => changeSong(1)}
      ></button>
    </ControlWrapper>
  )
}

export default memo(Control)